package userViews

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/sqlite"
	"goWeb/webUsers/userData"
	"net/http"
)

func Register(c *gin.Context) {
	username := c.Query("username")
	password := c.Query("password")

	db, _ := gorm.Open("sqlite3", "./goWeb.db")
	defer db.Close()
	//tmp_username := &userData.User{}
	var tmp_count int
	db.Model(&userData.User{}).Where("username = ?", username).Count(&tmp_count)
	fmt.Println(tmp_count)
	if tmp_count == 0 {
		db.Create(&userData.User{Username: username, Password: password})
		c.String(http.StatusOK,"user %s create.", username)
	} else {
		c.String(http.StatusBadRequest,"user %s exist.", username)
	}
}

func Login(c *gin.Context) {
	username := c.Query("username")
	password := c.Query("password")
	db, _ := gorm.Open("sqlite3", "./goWeb.db")
	defer db.Close()
	var tmp_count int
	db.Model(&userData.User{}).Where("Username = ? AND Password = ?", username, password).Count(&tmp_count)
	fmt.Println(tmp_count)
	if tmp_count > 0 {
		c.String(http.StatusOK,"user %s login success.", username)
	} else {
		c.String(http.StatusBadRequest,"username or password error.")
	}
}
